package cn.org.donald.sensitive.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.NumberToTextConverter;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author Donald
 * @since 2023-11-16 13:43:07
 **/
public class ExcelUtil {

    public static void doReplace(Workbook workbook, Path destPath, String regex) {
        try {
            int numberOfSheets = workbook.getNumberOfSheets();
            for (int i = 0; i < numberOfSheets; i++) {
                Sheet sheet = workbook.getSheetAt(i);
                sheet.forEach(r -> r.forEach(c -> {
                    String cellValString = getCellValString(c);
                    String replacement = StringUtil.replaceTargetToStar(cellValString, regex);
                    c.setCellValue(replacement);
                }));
            }
            try (OutputStream outputStream = Files.newOutputStream(destPath)) {
                workbook.write(outputStream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    System.err.println("流关闭异常");
                }
            }
        }
    }

    public static String getCellValString(Cell cell){
        CellType cellType = cell.getCellType();
        String val = "";
        if (CellType.STRING.equals(cellType)){
            val = cell.getStringCellValue();
        }else if (CellType.BOOLEAN.equals(cellType)){
            val = String.valueOf(cell.getBooleanCellValue());
        }else if (CellType.NUMERIC.equals(cellType)){
            val = NumberToTextConverter.toText(cell.getNumericCellValue());
        }
        return val;
    }
}
